/**
 * 点击行为埋点组件
 * @author lhx
 */

import React, { useCallback, useMemo, useRef } from 'react';
import { TouchableOpacity, View, TouchableOpacityProps } from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import { 
  ClickTrackerLhxProps, 
  EventPriority,
  ClickEventProperties 
} from '../types/trackingTypes';
import { 
  addEvent, 
  saveEventToStorageLhx,
  selectTrackingConfig,
  selectCurrentSession
} from '../../store/slices/trackingSliceLhx';
import TrackingServiceLhx from '../services/trackingServiceLhx';

interface ClickTrackerLhxComponentProps extends ClickTrackerLhxProps {
  // 扩展TouchableOpacity的属性
  touchableProps?: Omit<TouchableOpacityProps, 'onPress' | 'children'>;
  // 是否使用原生TouchableOpacity包装
  useWrapper?: boolean;
  // 自定义点击处理器
  onPress?: () => void;
  // 延迟追踪（毫秒）
  trackingDelay?: number;
  // 是否防重复点击
  preventDoubleClick?: boolean;
  // 防重复点击间隔（毫秒）
  doubleClickInterval?: number;
}

const ClickTrackerLhx: React.FC<ClickTrackerLhxComponentProps> = ({
  eventName,
  properties = {},
  priority = EventPriority.MEDIUM,
  disabled = false,
  onTrack,
  onPress,
  children,
  touchableProps = {},
  useWrapper = true,
  trackingDelay = 0,
  preventDoubleClick = true,
  doubleClickInterval = 500
}) => {
  const dispatch = useDispatch();
  const config = useSelector(selectTrackingConfig);
  const currentSession = useSelector(selectCurrentSession);
  
  // 防重复点击的引用
  const lastClickTime = useRef<number>(0);
  const trackingService = useMemo(() => TrackingServiceLhx.getInstance(), []);

  /**
   * 处理点击事件
   */
  const handlePress = useCallback(() => {
    // 检查是否禁用
    if (disabled || !config.enabled) {
      onPress?.();
      return;
    }

    // 防重复点击检查
    if (preventDoubleClick) {
      const now = Date.now();
      if (now - lastClickTime.current < doubleClickInterval) {
        return;
      }
      lastClickTime.current = now;
    }

    // 执行用户的点击处理器
    onPress?.();

    // 执行埋点追踪
    const trackClick = () => {
      try {
        // 获取当前页面信息
        const currentPage = trackingService.getCurrentPage();
        
        // 创建增强的属性对象
        const enhancedProperties: ClickEventProperties = {
          ...properties,
          // 添加自动属性
          clickTime: Date.now(),
          sessionDuration: Date.now() - currentSession.startTime,
          pageStack: currentSession.pageStack,
          // 如果有位置信息，添加相对位置
          ...(properties.position !== undefined && {
            relativePosition: currentSession.pageStack.length > 0 
              ? `${currentSession.pageStack[currentSession.pageStack.length - 1]}_${properties.position}`
              : `${currentPage}_${properties.position}`
          })
        };

        // 创建点击事件
        const clickEvent = trackingService.createClickEvent(
          eventName,
          enhancedProperties,
          {
            priority,
            page: currentPage,
            module: 'recommendation'
          }
        );

        // 验证事件
        if (!trackingService.validateEvent(clickEvent)) {
          console.warn('[ClickTrackerLhx] Invalid event, skipping tracking');
          return;
        }

        // 过滤敏感信息
        const sanitizedEvent = trackingService.sanitizeEvent(clickEvent);

        // 调试输出
        if (config.debugMode) {
          trackingService.debugEvent(sanitizedEvent);
        }

        // 添加到Redux store（内存缓存）
        dispatch(addEvent(sanitizedEvent));

        // 异步保存到本地存储
        dispatch(saveEventToStorageLhx(sanitizedEvent));

        // 调用回调函数
        onTrack?.(sanitizedEvent);

        // 如果是高优先级事件，立即尝试上传
        if (priority === EventPriority.HIGH) {
          // 这里可以触发立即上传逻辑
          console.log('[ClickTrackerLhx] High priority event, should upload immediately');
        }

      } catch (error) {
        console.error('[ClickTrackerLhx] Error tracking click event:', error);
      }
    };

    // 根据延迟设置执行追踪
    if (trackingDelay > 0) {
      setTimeout(trackClick, trackingDelay);
    } else {
      trackClick();
    }
  }, [
    disabled,
    config.enabled,
    config.debugMode,
    preventDoubleClick,
    doubleClickInterval,
    onPress,
    eventName,
    properties,
    priority,
    currentSession,
    trackingService,
    dispatch,
    onTrack,
    trackingDelay
  ]);

  // 如果不使用包装器，直接返回子组件，并通过ref传递点击处理器
  if (!useWrapper) {
    // 这种情况下，需要子组件自己处理点击事件
    // 可以通过React.cloneElement传递onPress
    if (React.isValidElement(children)) {
      return React.cloneElement(children as React.ReactElement<any>, {
        onPress: handlePress
      });
    }
    return <>{children}</>;
  }

  // 使用TouchableOpacity包装
  return (
    <TouchableOpacity
      onPress={handlePress}
      activeOpacity={0.7}
      {...touchableProps}
      // 确保disabled状态正确传递
      disabled={disabled || touchableProps.disabled}
    >
      {children}
    </TouchableOpacity>
  );
};

// 高阶组件版本，用于包装现有组件
export const withClickTrackingLhx = <P extends object>(
  WrappedComponent: React.ComponentType<P>
) => {
  return React.forwardRef<any, P & ClickTrackerLhxProps>((props, ref) => {
    const { eventName, properties, priority, disabled, onTrack, ...componentProps } = props;
    
    return (
      <ClickTrackerLhx
        eventName={eventName}
        properties={properties}
        priority={priority}
        disabled={disabled}
        onTrack={onTrack}
        useWrapper={false}
      >
        <WrappedComponent ref={ref} {...(componentProps as P)} />
      </ClickTrackerLhx>
    );
  });
};

// 预设的点击追踪组件
export const TrackedTouchableOpacityLhx: React.FC<
  TouchableOpacityProps & ClickTrackerLhxProps
> = ({ children, eventName, properties, priority, disabled, onTrack, ...touchableProps }) => {
  return (
    <ClickTrackerLhx
      eventName={eventName}
      properties={properties}
      priority={priority}
      disabled={disabled}
      onTrack={onTrack}
      touchableProps={touchableProps}
    >
      {children}
    </ClickTrackerLhx>
  );
};

// 用于包装View的点击追踪组件
export const TrackedViewLhx: React.FC<
  React.ComponentProps<typeof View> & ClickTrackerLhxProps
> = ({ children, eventName, properties, priority, disabled, onTrack, ...viewProps }) => {
  return (
    <ClickTrackerLhx
      eventName={eventName}
      properties={properties}
      priority={priority}
      disabled={disabled}
      onTrack={onTrack}
      touchableProps={{ style: viewProps.style }}
    >
      <View {...viewProps}>
        {children}
      </View>
    </ClickTrackerLhx>
  );
};

export default ClickTrackerLhx;